package com.scpii.api.common.xml;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.springframework.beans.factory.InitializingBean;

import com.scpii.api.common.Constants;
import com.thoughtworks.xstream.converters.SingleValueConverter;

public class XStreamDateConverter implements SingleValueConverter,
		InitializingBean {

	private DateFormat dateFormat;

	public DateFormat getDateFormat() {
		return dateFormat;
	}

	public void setDateFormat(DateFormat dateFormat) {
		this.dateFormat = dateFormat;
	}

	@SuppressWarnings("rawtypes")
	@Override
	public boolean canConvert(Class type) {
		return Date.class.isAssignableFrom(type);
	}

	@Override
	public String toString(Object obj) {
		return dateFormat.format(obj);
	}

	@Override
	public Object fromString(String str) {
		try {
			return dateFormat.parse(str);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		setDateFormat(new SimpleDateFormat(Constants.RFC3339_FORMAT));
	}
}
